<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Queue;
use think\Request;
use think\facade\View;
use app\validate\CheckLive;
use think\exception\ValidateException;
use EasyWeChat\Factory;


// 直播管理
class Live extends BaseController
{
    public function index()
    {
        return View::fetch();
    }

    public function load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $where = [];
        $get = $request->param();

        if (isset($get['title'])) {
            if (!empty($get['title'])) {
                $where[] = ['a.title', 'like', '%'.$get['title'].'%'];
            }
        }

        if (isset($get['teacher'])) {
            if (!empty($get['teacher'])) {
                $where[] = ['a.teacher_name', 'like','%'.$get['teacher'].'%'];
            }
        }

        if (isset($get['status'])) {
            if (!empty($get['status'])) {
                if ($get['status'] == 1) {
                    $where[] = ['a.start', '>', time()];
                }elseif ($get['status'] == 2) {
                    $where[] = ['a.start', '<=', time()];
                    $where[] = ['a.end', '>=', time()];
                }elseif ($get['status'] == 3) {
                    $where[] = ['a.end', '<', time()];
                }
            }
        }

        if (isset($get['time'])) {
            if (!empty($get['time'])) {
                $where[] = ['a.start', 'between', [strtotime($get['time']), strtotime($get['time'])+86399]];
            }
        }

        $where[] = ['a.status', '=', 1];

        $total = Db::table('o_live')
            ->alias('a')
            ->join('o_course b','a.courseid=b.courseid')
            ->where($where)
            ->group('a.id')
            ->count();

        $rows = Db::table('o_live')
            ->alias('a')
            ->join('o_course b','a.courseid=b.courseid')
            ->where($where)
            ->field('a.id, a.start, a.end, a.zb_status, a.courseid, a.image, a.title, a.open, a.playback, a.channelId, a.teacher_name, b.e_seminar')
            ->order('a.id', 'desc')
            ->group('a.id')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();
        foreach ($rows as &$v) {
            $v['study_total'] = Db::name('live_log')->where('live_id', '=', $v['id'])->group('userid')->count();
            if ($v['start'] > time()) {
                $v['status_name'] = '<span style="color: #009688;">未开始</span>';
            } else if(($v['start'] <= time()) && ($v['end'] >= time())) {
                $v['status_name'] = '<span style="color: #1E9FFF;">进行中</span>';
            } else if($v['end'] < time()) {
                $v['status_name'] = '<span style="color: #FF5722;">已结束</span>';
            }
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }



    public function exportLive(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $get = $request->get();
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '直播课数据'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['ID', '班级名称', '是否公开', '学习人数', '开课时间', '状态', '教员', '关联课程', '课程ID']);

        $where = [];

        if (isset($get['title'])) {
            if (!empty($get['title'])) {
                $where[] = ['a.title', 'like','%'.$get['title'].'%'];
            }
        }

        if (isset($get['teacher'])) {
            if (!empty($get['teacher'])) {
                $where[] = ['a.teacher_name', 'like','%'.$get['teacher'].'%'];
            }
        }

        if (isset($get['status'])) {
            if (!empty($get['status'])) {
                if ($get['status'] == 1) {
                    $where[] = ['a.start', '>', time()];
                }elseif ($get['status'] == 2) {
                    $where[] = ['a.start', '<=', time()];
                    $where[] = ['a.end', '>=', time()];
                }elseif ($get['status'] == 3) {
                    $where[] = ['a.end', '<', time()];
                }
            }
        }

        if (isset($get['time'])) {
            if (!empty($get['time'])) {
                $where[] = ['a.start', 'between', [strtotime($get['time']), strtotime($get['time'])+86399]];
            }
        }

        $where[] = ['a.status', '=', 1];

        $total = Db::table('o_live')
            ->alias('a')
            ->join('o_course b','a.courseid=b.courseid')
            ->where($where)
            ->group('a.id')
            ->count();

        $nums = 100; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;
            $rows = Db::table('o_live')
                ->alias('a')
                ->join('o_course b','a.courseid=b.courseid')
                ->where($where)
                ->field('a.id, a.start, a.end, a.zb_status, a.courseid, a.image, a.title, a.open, a.playback, a.channelId, a.teacher_name, b.e_seminar')
                ->order('a.id desc')
                ->group('a.id')
                ->limit($start, $nums)
                ->select()
                ->toArray();

            foreach ($rows as &$v){
                $study_total = Db::name('live_log')->where('live_id', '=', $v['id'])->group('userid')->count();
                if ($v['start'] > time()) {
                    $status_name = '未开始';
                } else if(($v['start'] <= time()) && ($v['end'] >= time())) {
                    $status_name = '进行中';
                } else if($v['end'] < time()) {
                    $status_name = '已结束';
                }
                $arr = [
                    $v['id'],
                    $v['title'],
                    $v['open'] == 1 ? '否' : '是',
                    $study_total,
                    date('Y-m-d H:i:s', $v['start']),
                    $status_name,
                    $v['teacher_name'],
                    $v['e_seminar'],
                    $v['courseid']
                ];
                fputcsv($fp, $arr);
            }

            //每1千条数据就刷新缓冲区
            ob_flush();
            flush();
        }
    }


    //+直播课开放OR不开放
    public function open(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        if (!$id) {
            return $this->outputAjax();
        }

        try {
            $inf = Db::name('live')->find($id);

            if (empty($inf)) {
                return $this->outputAjax('参数错误！');
            }

            if (!in_array($inf['open'], array(1, 2))) {
                return $this->outputAjax('参数错误[1]！');
            }

            $status = $inf['open'] == 1 ? 2 : 1;

            $update = array(
                'id' => $id,
                'open' => $status,
            );
            if(Db::name('live')->update($update)) {
                return $this->outputAjax('操作成功！',0);
            }
            return $this->outputAjax('操作失败！');
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }



    //+删除班级
    public function delete(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        $id = $post['id'];
        if (empty($id)) {
            return $this->outputAjax('请选择课程！');
        }

        try {
            if (!Db::name('live')->where('id', '=', $id)->update(['status' => 2])) {
                return $this->outputAjax('删除失败！');
            }
            return $this->outputAjax('删除成功！', 0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    protected function getMillisecond() {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }


    public function add()
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $teacher = Db::name('members')
            ->where('status', '=', 1)
            ->where('role', 'in', '2,3')
            ->field('id, userid, name')
            ->select();

        View::assign('teacher', $teacher);
        return View::fetch();
    }



    public function save(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        //$post = remove_xss($post);
        // 验证
        try {

            validate(CheckLive::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }
        Db::startTrans();

        try {

            $course_img = Db::name('course')->where('courseid', '=', $post['courseid'])->value('img');
            if (empty($course_img)) {
                $course_img = config('app.zhibo.url').config('app.default.course');
            } else {
                if(strpos($course_img,'http') === false) {
                    $course_img = config('app.zhibo.url'). $course_img;
                }
            }
            $name = Db::name('members')->where('id', '=', $post['teacher'])->value('name');
            $insert = array(
                'courseid'      => $post['courseid'],
                'title'         => $post['title'],
                'e_title'       => $post['e_title'],
                'teacher'       => $post['teacher'],
                'teacher_name'  => $name,
                'start'         => strtotime($post['start']),
                'end'           => strtotime($post['end']),
                'image'         => $course_img,
                'content'       => $post['content'],
                'playback'      => $post['playback'],
                'scene'      => $post['scene'],
                'range'         => $post['range'],
                'status'        => 1,
                'zb_status'     => 1,
                'add_time'      => time(),
                'update_time'   => time(),
                'deadline'   => $post['deadline'] == '' ? 30 : $post['deadline'],
            );
            $zb_id = Db::name('live')->insertGetId($insert);
            if (!$zb_id) {
                Db::rollback();
                return $this->outputAjax('创建失败[1]！');
            }
            //毫秒级时间戳
            $timestamp = $this->getMillisecond();

            //签名
            $string = md5(config('app.zhibo.AppSecret').'appId'.config('app.zhibo.appId').'timestamp'.$timestamp.config('app.zhibo.AppSecret'));
            $sign = strtoupper($string);
            $url = 'http://api.polyv.net/live/v3/channel/basic/create?appId='.config('app.zhibo.appId').'&sign='.$sign.'&timestamp='.$timestamp;

            $secretkey = create_rand_string(10);
            $publisher = Db::name('members')->where('id', '=', $insert['teacher'])->value('name');
            //请求参数
            $data = array(
                'basicSetting' => array(
                    'name' => $post['title'],
                    'scene' => $post['scene'],
                    'channelPasswd' => create_rand_string(10).mt_rand(1, 99),
                    'startTime' => strtotime($post['start'])*1000,
                    'publisher' => $publisher,
                    'coverImg' => $insert['image'],
                    'splashImg' => $insert['image'],
                    'desc' => $insert['content']
                ),
                'authSettings' => array(
                    array(
                        'rank' => 1,
                        'enabled' => 'Y',
                        'authType' => 'external',
                        'externalKey' => $secretkey,
                        'externalUri' => config('app.zhibo.url').'/qy_oauth2/externalAuth',
                        'externalRedirectUri' => config('app.zhibo.url').'/qy_oauth2/open',
                    ),
                ),
            );

            if ($insert['playback'] == 1) {
                $data['playbackSetting'] = array(
                    'globalSettingEnabled' => 'N',
                    'playbackEnabled' => 'Y',
                    'type' => 'single',
                    'origin' => 'record'
                );
            }
            $json_data = json_encode($data);

            // 设置请求头
            $head = array(
                'content-type: application/json'
            );
            // 创建频道
            $res = zhibo_http_post($url, $json_data, false, $head);

            $return_data = json_decode($res, true);
            if ($return_data['code'] != 200) {
                Db::rollback();
                return $this->outputAjax('创建失败[2]: '.$return_data['message']);
            }

            $update = array(
                'id' => $zb_id,
                'channelId' => $return_data['data']['channelId'],
                'url' => config('app.zhibo.zhiboUrl').'/watch/'.$return_data['data']['channelId'],
                'secretkey' => $secretkey,
            );


            if (!Db::name('live')->update($update)) {
                Db::rollback();
                return $this->outputAjax('创建失败[3]！');
            }

            Db::commit();
            return $this->outputAjax('创建成功！', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }


    public function edit(Request $request)
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $id = $request->get('id');

        $inf = Db::name('live')->find($id);

        $inf['start'] = date('Y-m-d H:i:s', $inf['start']);
        $inf['end'] = date('Y-m-d H:i:s', $inf['end']);
        $inf['content'] = html_entity_decode($inf['content']);
        $inf['course_name'] = Db::name('course')->where('courseid', '=', $inf['courseid'])->value('e_seminar');
        View::assign('inf',$inf);

        $teacher = Db::name('members')
            ->where('status', '=', 1)
            ->where('role', 'in', '2,3')
            ->field('id, userid, name')
            ->select();

        View::assign('teacher', $teacher);
        return View::fetch();
    }


    public function modify(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        //$post = remove_xss($post);

        // 验证
        try {

            validate(CheckLive::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        Db::startTrans();

        try {
//            $res = textDetection($post);
//            if ($res != '') {
//                return $this->outputAjax($res);
//            }

            $inf = Db::name('live')->find($post['id']);
            if (!$inf) {
                return $this->outputAjax('保存失败[0]！');
            }

            $course_img = Db::name('course')->where('courseid', '=', $post['courseid'])->value('img');
            if (empty($course_img)) {
                $course_img = config('app.zhibo.url').config('app.default.course');
            } else {
                if(strpos($course_img,'http') === false) {
                    $course_img = config('app.zhibo.url'). $course_img;
                }
            }
            $name = Db::name('members')->where('id', '=', $post['teacher'])->value('name');
            $update = array(
                'id'            => $post['id'],
                'courseid'      => $post['courseid'],
                'title'         => $post['title'],
                'e_title'       => $post['e_title'],
                'teacher'       => $post['teacher'],
                'teacher_name'  => $name,
                'start'         => strtotime($post['start']),
                'end'           => strtotime($post['end']),
                'image'         => $course_img,
                'content'       => $post['content'],
                'playback'      => $post['playback'],
                'scene'      => $post['scene'],
                'range'         => $post['range'],
                'update_time'   => time(),
                'deadline'   => $post['deadline'] == '' ? 30 : $post['deadline'],
            );
            if (!Db::name('live')->update($update)) {
                Db::rollback();
                return $this->outputAjax('保存失败[1]！');
            }


            //毫秒级时间戳
            $timestamp = $this->getMillisecond();

            //签名
            $string = md5(config('app.zhibo.AppSecret').'appId'.config('app.zhibo.appId').'channelId'.$inf['channelId'].'timestamp'.$timestamp.config('app.zhibo.AppSecret'));
            $sign = strtoupper($string);
            $url = 'http://api.polyv.net/live/v3/channel/basic/update?appId='.config('app.zhibo.appId').'&channelId='.$inf['channelId'].'&sign='.$sign.'&timestamp='.$timestamp;
            $publisher = Db::name('members')->where('id', '=', $update['teacher'])->value('name');
            //请求参数
            $data = array(
                'basicSetting' => array(
                    'name' => $post['title'],
                    'scene' => $post['scene'],
                    'startTime' => strtotime($post['start'])*1000,
                    'publisher' => $publisher,
                    'coverImg' => $update['image'],
                    'splashImg' => $update['image'],
                    'desc' => $update['content']
                ),
            );

            $json_data = json_encode($data);

            // 设置请求头
            $head = array(
                'content-type: application/json'
            );
            // 编辑频道
            $res = zhibo_http_post($url, $json_data, false, $head);

            $return_data = json_decode($res, true);

            if ($return_data['code'] != 200) {
                Db::rollback();
                return $this->outputAjax('保存失败[2]: '.$return_data['message']);
            }


            //毫秒级时间戳
            $timestamp = $this->getMillisecond();

            if ($update['playback'] == 1) {
                $data = array(
                    'globalSettingEnabled' => 'N',
                    'playbackEnabled' => 'Y',
                    'type' => 'single',
                    'origin' => 'record'
                );
                //签名
                $string = md5(config('app.zhibo.AppSecret').'appId'.config('app.zhibo.appId').'channelId'.$inf['channelId'].'globalSettingEnabled'.'N'.'origin'.'record'.'playbackEnabled'.'Y'.'timestamp'.$timestamp.'type'.'single'.config('app.zhibo.AppSecret'));
                $sign = strtoupper($string);
                $url = 'http://api.polyv.net/live/v3/channel/playback/set-setting?appId='.config('app.zhibo.appId').'&globalSettingEnabled=N'.'&playbackEnabled=Y'.'&type=single'.'&origin=record'.'&channelId='.$inf['channelId'].'&sign='.$sign.'&timestamp='.$timestamp;
            } else {
                //签名
                $string = md5(config('app.zhibo.AppSecret').'appId'.config('app.zhibo.appId').'channelId'.$inf['channelId'].'playbackEnabled'.'N'.'timestamp'.$timestamp.config('app.zhibo.AppSecret'));
                $sign = strtoupper($string);
                $url = 'http://api.polyv.net/live/v3/channel/playback/set-setting?appId='.config('app.zhibo.appId').'&playbackEnabled=N'.'&channelId='.$inf['channelId'].'&sign='.$sign.'&timestamp='.$timestamp;
                $data = array(
                    'playbackEnabled' => 'N',
                );
            }

            $json_data = json_encode($data);

            // 设置请求头
            $head = array(
                'content-type: application/json'
            );
            // 编辑频道回放
            $res = zhibo_http_post($url, $json_data, false, $head);

            $return_data = json_decode($res, true);
            if ($return_data['code'] != 200) {
                Db::rollback();
                return $this->outputAjax('保存失败[3]: '.$return_data['message']);
            }

            Db::commit();
            return $this->outputAjax('保存成功！', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }


    public function getQrCode(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->param('id');

        try {

            $app = Factory::miniProgram($this->mini_config);

            $page = 'pages/Me/pages/live/details';
            $response = $app->app_code->getUnlimit($id, [
                'page'  => $page,
                'width' => 280,
            ]);

            $time = time();
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->saveAs(runtime_path().'/storage', $time.'.png');
            }

            $blob = new Upload();
            $res = $blob->uploadBlob(runtime_path().'/storage/'.$filename, $filename, 'image/png', 'small');
            if ($res['code'] == 200) {
                $qr = $res['data'];
            } else {
                $qr = '';
            }
            //删除文件
            unlink(runtime_path() . 'storage/' . $filename);
            return $this->outputAjax('获取成功', 0, ['url' => $qr]);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    public function downloadQrCode(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->param('id');
        $title = $request->param('title');

        try {

            $app = Factory::miniProgram($this->mini_config);

            $page = 'pages/Me/pages/live/details';
            $response = $app->app_code->getUnlimit($id, [
                'page'  => $page,
                'width' => 1280,
            ]);

            $time = time();
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->saveAs(runtime_path().'/storage', $time.'.png');
            }

            $blob = new Upload();
            $res = $blob->uploadBlob(runtime_path().'/storage/'.$filename, $filename, 'image/png', 'small');
            if ($res['code'] == 200) {
                $qr = $res['data'];
            } else {
                $qr = '';
            }
            //删除文件
            unlink(runtime_path() . 'storage/' . $filename);

            $fileTmp = pathinfo($qr);
            $fileExt = $fileTmp['extension'];    //图片后缀名
            $filename = str_replace('.', '', $title);   //图片名称，可以任务设置图片名称
            $saveFileName = ($filename.'.'.$fileExt);
            $fp = fopen($qr,"r");
            //下载文件需要用到的头
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Content-Disposition: attachment; filename=".$saveFileName);
            $buffer = 1024;
            $file_count = 0;
            //向浏览器返回数据
            while (!feof($fp)) {
                $file_con = fread($fp,$buffer);
                $file_count += $buffer;
                echo $file_con;
            }
            fclose($fp);
            exit;
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    // 直播课学员
    public function members(Request $request)
    {
        $live_id = $request->get('id');
        View::assign('live_id',$live_id);
        return View::fetch();
    }


    public function getMembersList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $live_id = $request->get('live_id');
        $get = $request->get();

        $where = [];

        if (isset($get['keys'])) {
            if (!empty($get['keys'])) {
                $where[] = ['userid', 'like', '%'.$get['keys'].'%'];
            }
        }

        if (isset($get['sign_out'])) {
            if (!empty($get['sign_out'])) {
                $where[] = ['sign_out', '=', $get['sign_out']];
            }
        }

        if (isset($get['like'])) {
            if (!empty($get['like'])) {
                $where[] = ['like', '=', $get['like']];
            }
        }


        $where[] = ['live_id', '=', $live_id];

        $total = Db::name('live_user')
            ->where($where)
            ->count();

        $rows = Db::name('live_user')
            ->where($where)
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            if ($v['user_type'] == 1) {
                $member = Db::name('members')
                    ->where('userid', '=', $v['userid'])
                    ->field('name, userid, department_name, division, mobile')
                    ->find();
                if ($member) {
                    $count = mb_strlen($member['userid']);
                    if ($count == 6) {
                        if (is_numeric($member['userid'])) {
                            $v['userid'] = '00'.$member['userid'];
                        } else {
                            $v['userid'] = $member['userid'];
                        }
                    } else {
                        $v['userid'] = $member['userid'];
                    }
                    $v['name'] = $member['name'];
                    $v['department_name'] = $member['department_name'];
                    $v['division'] = $member['division'];
                    $v['mobile'] = decrypts($member['mobile']);
                } else {
                    $v['name'] = '';
                    $v['department_name'] = '';
                    $v['division'] = '';
                    $v['mobile'] = '';
                }
            } else {
                $v['name'] = '';
                $v['department_name'] = '';
                $v['division'] = '';
                $v['mobile'] = '';
            }

        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    public function export(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $get = $request->get();
        $live_id = $request->get('live_id');
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '直播课学员数据'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['工号', '姓名', '手机号', 'Division', '部门', '注册类型', '已退出', '我的最爱', '学员类型']);

        $where = [];

        if (isset($get['keys'])) {
            if (!empty($get['keys'])) {
                $where[] = ['userid', 'like', '%'.$get['keys'].'%'];
            }
        }

        if (isset($get['sign_out'])) {
            if (!empty($get['sign_out'])) {
                $where[] = ['sign_out', '=', $get['sign_out']];
            }
        }

        if (isset($get['like'])) {
            if (!empty($get['like'])) {
                $where[] = ['like', '=', $get['like']];
            }
        }


        $where[] = ['live_id', '=', $live_id];

        $total = Db::name('live_user')
            ->where($where)
            ->count();

        $nums = 100; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;
            $rows = Db::name('live_user')
                ->where($where)
                ->limit($start, $nums)
                ->select()
                ->toArray();

            foreach ($rows as &$v){

                if ($v['user_type'] == 1) {
                    $member = Db::name('members')
                        ->where('userid', '=', $v['userid'])
                        ->field('name, userid, department_name, division, mobile')
                        ->find();
                    if ($member) {
                        $count = mb_strlen($member['userid']);
                        if ($count == 6) {
                            if (is_numeric($member['userid'])) {
                                $userid = "'00".$member['userid'];
                            } else {
                                $userid = $member['userid'];
                            }
                        } else {
                            $userid = $member['userid'];
                        }
                        $name = $member['name'];
                        $department_name = $member['department_name'];
                        $division = $member['division'];
                        $mobile = decrypts($member['mobile']);
                    } else {
                        $userid = $v['userid'];
                        $name = '';
                        $department_name = '';
                        $division = '';
                        $mobile = '';
                    }
                } else {
                    $userid = $v['userid'];
                    $name = '';
                    $department_name = '';
                    $division = '';
                    $mobile = '';
                }


                $type = '';
                if ($v['type'] == 1) {
                    $type = '后台导入';
                } elseif ($v['type'] == 2) {
                    $type = '小程序注册';
                } elseif ($v['type'] == 3) {
                    $type = 'PC端注册';
                }

                $arr = [
                    $userid,
                    $name,
                    $mobile,
                    $division,
                    $department_name,
                    $type,
                    $v['sign_out'] == 1 ? '否' : '是',
                    $v['like'] == 1 ? '否' : '是',
                    $v['user_type'] == 1 ? '小程序学员' : '国外学员',
                ];
                fputcsv($fp, $arr);
            }
            //每1千条数据就刷新缓冲区
            ob_flush();
            flush();
        }
    }

    // 删除学员
    public function deleteMembers(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->param('id');

        if (!$id) {
            return $this->outputAjax('参数不足！');
        }

        $id = explode(',',trim($id,','));

        Db::startTrans();
        try {
            foreach ($id as $key => $value) {
                $zhibo_user = Db::name('live_user')->where('id', '=', $value)->find();
                if (!$zhibo_user) {
                    return $this->outputAjax('参数错误！');
                }
                if (!Db::name('live_user')->where('id', '=', $value)->delete()) {
                    Db::rollback();
                    return $this->outputAjax('删除失败[1]！');
                }

                $res = Db::name('live_log')
                    ->where('userid', '=', $zhibo_user['userid'])
                    ->where('live_id', '=', $zhibo_user['live_id'])
                    ->find();

                if ($res) {
                    if (!Db::name('live_log')->where('userid', '=', $zhibo_user['userid'])->delete()) {
                        Db::rollback();
                        return $this->outputAjax('删除失败[2]！');
                    }
                }
            }

            Db::commit();
            return $this->outputAjax('删除成功！', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    public function user(Request $request)
    {
        $live_id = $request->param('live_id');
        View::assign('live_id', $live_id);
        return View::fetch();
    }

    public function saveUser(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $live_id = $request->post('live_id');
        $uid = $request->post('id');

        if(!$live_id){
            return $this->outputAjax('缺少班级id！');
        }

        try {
            $uids = explode(',',$uid);
            if(!is_array($uids) || count($uids) <= 0){
                return $this->outputAjax('请选择学员！');
            }


            $zhibo = Db::name('live')->find($live_id);

            $t = [];
            $t['live_id'] = $live_id;
            $t['channelId'] = $zhibo['channelId'];
            $t['add_time'] = time();

            foreach ($uids as $key => $value) {
                $user = Db::name('members')
                    ->where('id', '=', $value)
                    ->field('id, userid, language, name, openid')
                    ->find();
                $res = Db::name('live_user')
                    ->where('userid', '=', $user['userid'])
                    ->where('live_id', '=', $live_id)
                    ->find();
                if($res){
                    continue;
                }
                $t['userid'] = $user['userid'];
                $t['openid'] = $user['openid'];
                Db::name('live_user')->insert($t);
            }
            return $this->outputAjax('添加成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    //文件批量导入学员
    public function import(Request $request)
    {
        $live_id = $request->param('live_id');
        View::assign('live_id', $live_id);
        return View::fetch();
    }


    public function executeImport(Request $request)
    {
        if (!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限', 2);
        }

        set_time_limit(0);

        $filename = $request->param('path');

        $live_id = $request->param('live_id');

        if(empty($live_id)) {
            return $this->outputAjax('参数缺失', 2);
        }
        $zhibo = Db::name('live')->where('id', '=', $live_id)->find();
        if(!$zhibo) {
            return $this->outputAjax('课程不存在', 2);
        }

        try {

            // 获取excel表格数据
            $result = get_excel_info($filename);
            if ($result['code'] == 1) {
                return $this->outputAjax($result['msg'], 2);
            }

            $i = 0;
            foreach ($result['data'] as $key => $value) {
                $userid = $value[0];
                $user_type = $value[1];

                if ($user_type == 1) {
                    $user = Db::name('members')
                        ->where('userid', '=', $userid)
                        ->field('id, userid, language, name, openid')
                        ->find();
                    if (!$user) {
                        continue;
                    }

                    $res = Db::name('live_user')
                        ->where('userid', '=', $userid)
                        ->where('live_id', '=', $live_id)
                        ->find();
                    if($res) {
                        continue;
                    }

                    $newValue = [
                        'live_id' => $live_id,
                        'channelId' => $zhibo['channelId'],
                        'add_time' => time(),
                        'user_type' => $user_type,
                        'userid' => $userid,
                        'openid' => $user['openid']
                    ];
                    $f = Db::name('live_user')->insert($newValue);
                    if ($f) {
                        $i++;
                    }
                } else {

                    $res = Db::name('live_user')
                        ->where('userid', '=', $userid)
                        ->where('live_id', '=', $live_id)
                        ->find();
                    if($res) {
                        continue;
                    }

                    $newValue = [
                        'live_id' => $live_id,
                        'channelId' => $zhibo['channelId'],
                        'add_time' => time(),
                        'user_type' => $user_type,
                        'userid' => $userid,
                        'openid' => $userid
                    ];
                    $f = Db::name('live_user')->insert($newValue);
                    if ($f) {
                        $i++;
                    }
                }

            }
            return $this->outputAjax('导入成功！', 0, [$i, count($result['data'])-$i]);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage(), 2);
        }
    }


    public function sendEmail(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }
        $post = $request->post();

        try {
            $inf = Db::name('live')
                ->where('id', '=', $post['live_id'])
                ->field('id, title, start, channelId, url')
                ->find();

            $inf['start'] = date('Y-m-d H:i',$inf['start']);

            if ($post['type'] == 0) {

                if (empty($post['email'])) {
                    return $this->outputAjax('请输入邮箱');
                }

                $to_address = $post['email'];

                $desc = '老师，您好:<br/>
                Dear Teacher,<br/>
                <br/>
                <br/>
                您有一门直播课《'.$inf['title'].'》将于'.$inf['start'].'开播，届时您可以使用PC Chrome 58 以上版本浏览器开启直播。<br/>
                Your live streaming course: ”'.$inf['title'].'” will be started at '.$inf['start'].'. Please start your course via PC Chrome browser(above version 58)  with below credentials:<br/>
    
                https://live.polyv.net/web-start/?channelId='.$inf['channelId'].'<br/>
    
                建议您提前30分钟进入直播间进行设备调试和准备。<br/>
                Kindly Remind: Login broadcasting room 30 minutes in advance and test your camera / microphone device will be highly recommended<br/>
                <br/>
                <br/>
                您可以打开附件中的日历项文件，快捷地将其添加到您的日历中。<br/>
                You can open the calendar.ics as attached to add this course to your calendar.<br/>
                <br/>
                <br/>
                如果直播主讲人是外部讲师，请将此邮件转发给对应外部讲师，由外部讲师登录开启直播。<br/>
                If you are not host of this live streaming course, please forward this mail to the appropriate teacher, or contact training admin in your company.<br/>';
            } else {

                $data = Db::table('o_live_user')
                    ->alias('a')
                    ->join('o_members b','b.userid=a.userid')
                    ->where('a.sign_out', '=', 1)
                    ->where('a.user_type', '=', 1)
                    ->where('a.live_id', '=', $post['live_id'])
                    ->column('b.email');

                $to_address = [];
                foreach ($data as &$v) {
                    if (!empty(decrypts($v))) {
                        array_push($to_address, decrypts($v));
                    }
                }

                $data = Db::name('live_user')
                    ->where('user_type', '=', 2)
                    ->where('live_id', '=', $post['live_id'])
                    ->column('userid');

                foreach ($data as &$v) {
                    array_push($to_address, $v);
                }

                $desc = '学员 你好，<br/>
                Dear learner,<br/>
                <br/>
                <br/>
                您有一门直播课《'.$inf['title'].'》将于'.$inf['start'].'开播，届时请登录学习平台进入课程学习页面参与直播。<br/>
                Your live streaming course: ”'.$inf['title'].'” will be started at '.$inf['start'].'. Please login to mobile LMS to find and join this course.<br/>
                <br/>
                <br/>
                您可以打开附件中的日历项文件，快捷地将其添加到您的日历中。<br/>
                You can open the calendar.ics as attached to add this course to your calendar.<br/>';
            }
            $startdate = date('Ymd', strtotime($inf['start'])).'T'.date('His', strtotime($inf['start']));
            if ($post['type'] == 0) {
                $url = 'https://live.polyv.net/web-start/?channelId='.$inf['channelId'];
            } else {
                $url = $inf['url'];
            }
            $content = 'BEGIN:VCALENDAR
            CALSCALE:GREGORIAN
            VERSION:2.0
            METHOD:PUBLISH
            PRODID:-//Apple Inc.//Mac OS X 10.15.7//EN
            BEGIN:VTIMEZONE
            TZID:Asia/Shanghai
            BEGIN:STANDARD
            TZOFFSETFROM:+0800
            RRULE:FREQ=YEARLY;UNTIL=19910914T170000Z;BYMONTH=9;BYDAY=3SU
            DTSTART:19890917T020000
            TZNAME:GMT+8
            TZOFFSETTO:+0800
            END:STANDARD
            BEGIN:DAYLIGHT
            TZOFFSETFROM:+0800
            DTSTART:19910414T020000
            TZNAME:GMT+8
            TZOFFSETTO:+0800
            RDATE:19910414T020000
            END:DAYLIGHT
            END:VTIMEZONE
            BEGIN:VEVENT
            TRANSP:OPAQUE
            UID:AB08AE78-BC59-43E3-AB3F-51D3D09DFF4E
            DTSTAMP:20210518T074652Z
            DESCRIPTION:《'.$inf['title'].'》直播课程
            URL;VALUE=URI:'.$url.'
            SEQUENCE:1
            X-APPLE-TRAVEL-ADVISORY-BEHAVIOR:AUTOMATIC
            SUMMARY:《'.$inf['title'].'》直播课程
            LAST-MODIFIED:20210518T074652Z
            CREATED:20210518T074613Z
            DTSTART;TZID=Asia/Shanghai:'.$startdate.'
            END:VEVENT
            END:VCALENDAR';


            $accept = 'text/calendar';


            $from = array(
                config('mail.username') => config('mail.name'),
            );;
            require_once root_path().'/vendor/autoload.php';



            $transport = (new \Swift_SmtpTransport(config('mail.hostname'), config('mail.port'), config('mail.security')))
                ->setUsername(config('mail.username'))
                ->setPassword(config('mail.password'));

            $mailer = new \Swift_Mailer($transport);
            $message = (new \Swift_Message())
                ->setSubject($post['theme'])
                ->setFrom($from)
                ->setTo($to_address)
                ->setContentType(config('mail.content_type'))
                ->setCharset(config('mail.charset'))
                ->setBody($desc)
                ->attach(new \Swift_Attachment($content, $inf['title'].'.ics', $accept));

            $res = $mailer->send($message);
            if ($post['type'] == 1) {
                if ($res != 1) {
                    return $this->outputAjax('邮件发送失败！');
                }

                return $this->outputAjax('邮件发送成功！', 0);
            } else {
                if ($res < 1) {
                    return $this->outputAjax('邮件发送失败！');
                }

                return $this->outputAjax('邮件发送成功！', 0);
            }
        }catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }



    public function callback(Request $request)
    {
        $live_id = $request->get('id');

        View::assign('live_id', $live_id);
        return View::fetch();
    }

    //回放数据加载
    public function getCallbackList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $live_id = $request->get('live_id');

        $inf = Db::name('live')->find($live_id);

        if (!$inf) {
            $data = array(
                'code'=> 1,
                'msg'=> '参数错误',
                'count' => 0,
                'data'=> []
            );
            return json($data);
        }

        //毫秒级时间戳
        $timestamp = $this->getMillisecond();

        //签名
        $string = md5(config('app.zhibo.AppSecret').'appId'.config('app.zhibo.appId').'timestamp'.$timestamp.'userId'.config('app.zhibo.userId').config('app.zhibo.AppSecret'));
        $sign = strtoupper($string);

        //请求url
        $url = 'http://api.polyv.net/live/v2/channels/'.$inf['channelId'].'/recordFiles?appId='.config('app.zhibo.appId').'&sign='.$sign.'&timestamp='.$timestamp.'&userId='.config('app.zhibo.userId');


        // 获取频道暂存回放视频
        $res = zhibo_http_get($url);

        $data = json_decode($res, true);

        foreach ($data['data'] as &$v) {
            $v['startTime'] = date('Y-m-d H:i:s', strtotime($v['startTime']));
            $v['endTime'] = date('Y-m-d H:i:s', strtotime($v['endTime']));
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => 0,
            'data'=> $data['data']
        );
        return json($data);
    }


    public function record()
    {
        return View::fetch();
    }


    public function getRecordList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $where = [];
        if (isset($get['tree_select_nodeId'])) {
            if (!empty($get['tree_select_nodeId'])) {
                $department = $get['tree_select_nodeId'];
                $arr = get_children($department, 1);
                $arr[] = $department;
                $department = implode('|', $arr);
                $where[]  = ['', 'EXP', Db::raw("CONCAT(',',b.department,',') REGEXP concat(',(',replace('".$department."',',','|'),'),')")];
            }
        }

        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['b.name|b.userid', 'like', '%' . $get['key'] . '%'];
            }
        }
        $where[] = ['b.status', '=', 1];

        $where1 = [];
        if (isset($get['time'])) {
            if (!empty($get['time'])) {
                $t = explode(' - ', $get['time']);
                $where1[] = ['date', '>=', date('Ymd', strtotime($t[0]))];
                $where1[] = ['date', '<=', date('Ymd', strtotime($t[1]))];
                session('live_record_time', $get['time']);
            } else {
                session('live_record_time', '');
            }
        } else {
            session('live_record_time', '');
        }


        session('live_record_where', $where);

        // 取得满足条件的记录数

        $subQuery1 = Db::table('o_live_log')
            ->field('SUM(time) as duration, userid')
            ->where($where1)
            ->group('userid')
            ->buildSql();

        $total = Db::table('o_live_user')
            ->alias('a')
            ->join('o_members b','b.userid=a.userid','left')
            ->join($subQuery1.'c','a.userid=c.userid','left')
            ->where($where)
            ->group('a.userid')
            ->count();

        // 分页查询数据
        $rows = Db::table('o_live_user')
            ->alias('a')
            ->join('o_members b','b.userid=a.userid','left')
            ->join($subQuery1.'c','a.userid=c.userid','left')
            ->where($where)
            ->group('a.userid')
            ->page($get['page'], $get['limit'])
            ->field('b.name, b.userid, b.department_name, b.division, b.openid, c.duration')
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            if (empty($v['duration'])) {
                $v['duration'] = 0;
            }

            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                }
            }
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    //+导出课程学习明细
    public function exportRecord()
    {
        if (!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $res = Db::name('document')->where('type', '=', 'LiveRecordJobQueue')->where('url', '=', '')->find();

        if ($res) {
            return $this->outputAjax('已有下载任务, 请勿重复操作');
        }


        Db::startTrans();
        try {
            $live_record_where = session('live_record_where');
            $live_record_time = session('live_record_time');

            $start = '';
            $end = '';
            $where1 = [];
            if (isset($live_record_time)) {
                if (!empty($live_record_time)) {
                    $t = explode(' - ', $live_record_time);
                    $where1[] = ['date', '>=', date('Ymd', strtotime($t[0]))];
                    $where1[] = ['date', '<=', date('Ymd', strtotime($t[1]))];
                    $start = $t[0];
                    $end = $t[1];
                }
            }

            $where = [];

            if (isset($live_record_where['tree_select_nodeId'])) {
                if (!empty($live_record_where['tree_select_nodeId'])) {
                    $department = $live_record_where['tree_select_nodeId'];

                    $arr = get_children($department, 1);
                    $arr[] = $department;
                    $department = implode('|', $arr);
                    $where[]  = ['', 'EXP', Db::raw("CONCAT(',',b.department,',') REGEXP concat(',(',replace('".$department."',',','|'),'),')")];
                }
            }

            if (isset($live_record_where['key'])) {
                if (!empty($live_record_where['key'])) {
                    $where[] = ['b.name|b.userid', 'like', '%' . $live_record_where['key'] . '%'];
                }
            }

            $where[] = ['b.status', '=', 1];
            $subQuery1 = Db::table('o_live_log')
                ->field('SUM(time) as duration, userid')
                ->where($where1)
                ->group('userid')
                ->buildSql();

            $members = Db::table('o_live_user')
                ->alias('a')
                ->join('o_members b','b.userid=a.userid','left')
                ->join($subQuery1.'c','a.userid=c.userid','left')
                ->where($where)
                ->group('a.userid')
                ->field('b.id as members_id, b.name, b.userid, b.department_name, b.division, b.openid')
                ->select()
                ->toArray();

            foreach ($members as &$v) {
                $v['add_time'] = time();
                $v['type'] = 'LiveRecordJobQueue';
            }

            if (!Db::name('temporary_members')->insertAll($members)) {
                Db::rollback();
                return $this->outputAjax('任务添加失败[1]');
            }

            $ts = time();

            $insert = array(
                'admin_id' => session('admin_auth.id'),
                'title' => '直播课课程学习明细-'.date('YmdHis', $ts),
                'url' => '',
                'type' => 'LiveRecordJobQueue',
                'add_time' => $ts
            );

            $download_id = Db::name('document')->insertGetId($insert);
            if (!$download_id) {
                Db::rollback();
                return $this->outputAjax('任务添加失败[2]');
            }

            // 1.当前任务由哪个类来负责处理
            // 当轮到该任务时，系统将生成该类的实例，并调用其fire方法
            $jobHandlerClassNameTask1 = 'app\job\JobLive@task1';

            // 2.当任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueNameTask1 = "LiveRecordJobQueueTask1";


            // 3.当前任务所需业务数据，不能为resource类型，其他类型最终将转化为json形式的字符串
            $jobData = ['ts' => $ts, 'download_id' => $download_id, 'page' => 1, 'start' => $start, 'end' => $end];

            // 4.将该任务推送到消息列表，等待对应的消费者去执行
            // 入队列，later延迟执行，单位秒，push立即执行
            $isPushedTask1 = Queue::push($jobHandlerClassNameTask1, $jobData, $jobQueueNameTask1);

            // database 驱动时，返回值为 1|false  ;   redis 驱动时，返回值为 随机字符串|false
            if ($isPushedTask1 !== false) {

                Db::commit();
                return $this->outputAjax('任务添加成功, 稍后在下载中心查看', 0);

            } else {

                Db::rollback();
                return $this->outputAjax('任务添加失败');

            }
        } catch (\Exception $e) {

            Db::rollback();
            return $this->outputAjax($e->getMessage());

        }

    }

    //+导出员工课程学习明细
    public function exportUserRecord()
    {
        if (!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $res = Db::name('document')->where('type', '=', 'LiveUserRecordJobQueue')->where('url', '=', '')->find();

        if ($res) {
            return $this->outputAjax('已有下载任务, 请勿重复操作');
        }


        Db::startTrans();
        try {
            $live_record_where = session('live_record_where');

            $live_record_time = session('live_record_time');

            $start = '';
            $end = '';
            $where1 = [];
            if (isset($live_record_time)) {
                if (!empty($live_record_time)) {
                    $t = explode(' - ', $live_record_time);
                    $where1[] = ['date', '>=', date('Ymd', strtotime($t[0]))];
                    $where1[] = ['date', '<=', date('Ymd', strtotime($t[1]))];
                    $start = $t[0];
                    $end = $t[1];
                }
            }

            $where = [];

            if (isset($live_record_where['tree_select_nodeId'])) {
                if (!empty($live_record_where['tree_select_nodeId'])) {
                    $department = $live_record_where['tree_select_nodeId'];

                    $arr = get_children($department, 1);
                    $arr[] = $department;
                    $department = implode('|', $arr);
                    $where[]  = ['', 'EXP', Db::raw("CONCAT(',',b.department,',') REGEXP concat(',(',replace('".$department."',',','|'),'),')")];
                }
            }

            if (isset($live_record_where['keys'])) {
                if (!empty($live_record_where['keys'])) {
                    $where[] = ['b.name|b.userid', 'like', '%' . $live_record_where['keys'] . '%'];
                }
            }

            $where[] = ['b.status', '=', 1];

            $subQuery1 = Db::table('o_live_log')
                ->field('SUM(time) as duration, userid')
                ->where($where1)
                ->group('userid')
                ->buildSql();

            $members = Db::table('o_live_user')
                ->alias('a')
                ->join('o_members b','b.userid=a.userid','left')
                ->join($subQuery1.'c','a.userid=c.userid','left')
                ->where($where)
                ->group('a.userid')
                ->field('b.id as members_id, b.name, b.userid, b.department_name, b.division, b.openid')
                ->select()
                ->toArray();

            foreach ($members as &$v) {
                $v['add_time'] = time();
                $v['type'] = 'LiveUserRecordJobQueue';
            }

            if (!Db::name('temporary_members')->insertAll($members)) {
                Db::rollback();
                return $this->outputAjax('任务添加失败[1]');
            }

            $ts = time();

            $insert = array(
                'admin_id' => session('admin_auth.id'),
                'title' => '直播课员工学习明细-'.date('YmdHis', $ts),
                'url' => '',
                'type' => 'LiveUserRecordJobQueue',
                'add_time' => $ts
            );

            $download_id = Db::name('document')->insertGetId($insert);
            if (!$download_id) {
                Db::rollback();
                return $this->outputAjax('任务添加失败[2]');
            }

            // 1.当前任务由哪个类来负责处理
            // 当轮到该任务时，系统将生成该类的实例，并调用其fire方法
            $jobHandlerClassNameTask2 = 'app\job\JobLive@task2';

            // 2.当任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueNameTask2 = "LiveUserRecordJobQueueTask2";


            // 3.当前任务所需业务数据，不能为resource类型，其他类型最终将转化为json形式的字符串
            $jobData = ['ts' => $ts, 'download_id' => $download_id, 'page' => 1, 'start' => $start, 'end' => $end];

            // 4.将该任务推送到消息列表，等待对应的消费者去执行
            // 入队列，later延迟执行，单位秒，push立即执行
            $isPushedTask1 = Queue::push($jobHandlerClassNameTask2, $jobData, $jobQueueNameTask2);

            // database 驱动时，返回值为 1|false  ;   redis 驱动时，返回值为 随机字符串|false
            if ($isPushedTask1 !== false) {

                Db::commit();
                return $this->outputAjax('任务添加成功, 稍后在下载中心查看', 0);

            } else {

                Db::rollback();
                return $this->outputAjax('任务添加失败');

            }
        } catch (\Exception $e) {

            Db::rollback();
            return $this->outputAjax($e->getMessage());

        }

    }



    //培训安排
    public function step(Request $request)
    {
        $live_id = $request->get('live_id');

        if (!$live_id) {
            return $this->outputAjax('参数不足！');
        }

        $data = Db::name('live_step')
            ->where('live_id', '=', $live_id)
            ->order(['sort'=>'asc', 'add_time'=>'desc'])
            ->select()
            ->toArray();

        foreach ($data as &$v) {
            $resource = Db::name('live_step_resource')
                ->alias('a')
                ->join('o_courseware b', 'a.courseware_id=b.id','left')
                ->field('a.id, a.live_id, a.add_time, b.title, b.duration, b.type, b.id as courseware_id')
                ->where('a.live_id', '=', $live_id)
                ->where('a.status', '=', 1)
                ->where('a.step_id', '=', $v['id'])
                ->order(['a.sort'=> 'asc','a.add_time'=> 'asc'])
                ->select()
                ->toArray();

            foreach ($resource as &$val) {
                $val['duration'] = $val['duration'] ? sprintf("%.2f", $val['duration']/60):'';
                if ($val['type'] == 1) {
                    $val['type_name'] = '<span style="color: #1E9FFF;">图文</span>';
                } elseif ($val['type'] == 2) {
                    $val['type_name'] = '<span style="color: #FFB800;">文档</span>';
                } elseif ($val['type'] == 5) {
                    $val['type_name'] = '<span style="color: #2D8CF0;">外链</span>';
                } else {
                    $val['type_name'] = '';
                }
                $val['add_time'] = date('Y-m-d H:i:s', $val['add_time']);

                $val['end_time'] = '';

                if ($val['type'] == 4) {
                    $end_time = Db::name('courseware_survey')->where('courseware_id', '=', $val['courseware_id'])->value('end_time');
                    $val['end_time'] = $end_time == ''? '':date('Y-m-d H:i:s', $end_time);
                }
            }
            $v['resource'] = $resource;
        }

        View::assign('live_id', $live_id);
        View::assign('data', $data);
        return View::fetch();
    }


    //+新增学习单元
    public function saveUnit(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        try {
            $data = array(
                'live_id' => $post['live_id'],
                'name' => $post['unit'],
                'add_time' => time(),
            );

            if (!Db::name('live_step')->insert($data)) {
                return $this->outputAjax('新增失败！');
            } else {
                return $this->outputAjax('新增成功！', 0);
            }
            Db::name('live')->where('id', '=', $post['live_id'])->update(['update_time'=>time()]);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }

    }


    //+修改学习单元
    public function modifyUnit(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        try {
            $data = array(
                'id' => $post['id'],
                'name' => $post['unit'],
            );

            if (!Db::name('live_step')->update($data)) {
                return $this->outputAjax('修改失败！');
            } else {
                return $this->outputAjax('修改成功！', 0);
            }
            Db::name('live')->where('id', '=', $post['live_id'])->update(['update_time'=>time()]);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }

    }


    //+删除学习单元
    public function deleteUnit(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        if (!$id) {
            return $this->outputAjax('非法参数！');
        }

        try {
            $res = Db::name('live_step_resource')->where('step_id', '=', $id)->where('status', '=', 1)->find();
            if ($res) {
                return $this->outputAjax('该单元下有任务，无法删除！');
            }

            if (!Db::name('live_step')->where('id', '=', $id)->delete()) {
                return $this->outputAjax('删除失败！');
            }

            return $this->outputAjax('删除成功！', 0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    //+单元排序
    public function sortUnit(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $sortstr = $request->post('sortstr');

        if (empty($sortstr)) {
            return $this->outputAjax('参数不足！');
        }

        try {

            $sortarr = explode(',', $sortstr);

            foreach ($sortarr as $key => $val) {
                Db::name('live_step')->where('id', '=', $val)->update(['sort' => $key+1]);
            }
            return $this->outputAjax('排序成功！', 0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    // 选择课件
    public function courseware(Request $request)
    {
        $live_id = $request->get('live_id');
        $unit_id = $request->get('unit_id');
        $cate = Db::name('courseware_cate')->where('status', '=', 1)->field('id, title')->select();
        $label = Db::name('courseware_label')->where('status', '=', 1)->field('id, title')->select();

        View::assign('cate', $cate);
        View::assign('label', $label);
        View::assign('live_id', $live_id);
        View::assign('unit_id', $unit_id);

        return View::fetch();
    }


    public function getCoursewareList(Request $request)
    {
        $get = $request->get();

        $where = [];

        if (isset($get['title'])) {
            if (!empty($get['title'])) {
                $where[] = ['a.title|a.e_title', 'like', '%'.$get['title'].'%'];
            }
        }

        if (isset($get['cate_id'])) {
            if (!empty($get['cate_id'])) {
                $where[] = ['a.cate_id', '=', $get['cate_id']];
            }
        }

        if (isset($get['label_id'])) {
            if (!empty($get['label_id'])) {
                $label_id = $get['label_id'];
                $where[] = ['','EXP',Db::raw('FIND_IN_SET("'.$label_id.'",a.label_id)')];
            }
        }


        if (isset($get['type'])) {
            if (!empty($get['type'])) {
                $where[] = ['a.type', '=', $get['type']];
            } else {
                $where[] = ['a.type', 'in', '1,2,5'];
            }

        } else {
            $where[] = ['a.type', 'in', '1,2,5'];
        }

        if (isset($get['time'])) {
            if (!empty($get['time'])) {
                $t = explode(' - ', $get['time']);
                $where[] = ['a.add_time', 'between', [strtotime($t[0]), strtotime($t[1])+86399]];
            }
        }

        if (!is_admin()) {
            $id = Db::name('courseware')->where('user_id', '<>', $this->user_id)->where('open', '=', 2)->column('id');
            $where[] = ['a.id', 'not in', $id];
        }

        $where[] = ['a.status', '=', 1];

        $total = Db::name('courseware')
            ->alias('a')
            ->join('courseware_cate b', 'b.id=a.cate_id', 'left')
            ->where($where)
            ->count();

        $rows = Db::name('courseware')
            ->alias('a')
            ->join('o_courseware_cate b', 'b.id=a.cate_id', 'left')
            ->where($where)
            ->field('a.id, a.title, a.e_title, a.cate_id, a.label_id, a.type, a.duration, a.add_time, a.open, a.user_id, b.title as cate_name')
            ->order('a.add_time', 'desc')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            $label_name = Db::name('courseware_label')->where('id', 'in', $v['label_id'])->column('title');
            $v['label_name'] = implode('|', $label_name);

            $account = Db::name('admin_user')->where('id', '=', $v['user_id'])->field('givenname, surname')->find();
            $v['account'] = $account['givenname'].' '.$account['surname'];
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    // 保存课件
    public function saveCourseware(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $live_id = $request->post('live_id');
        $unit_id = $request->post('unit_id');
        $id = $request->post('id');

        if(!$live_id) {
            return $this->outputAjax('缺少课程id！');
        }

        if(!$unit_id) {
            return $this->outputAjax('缺少单元id！');
        }

        Db::startTrans();
        try {

            $ids = explode(',',$id);
            if(!is_array($ids) || count($ids) <= 0){
                return $this->outputAjax('请选择课件！');
            }


            $t = [];
            $t['live_id'] = $live_id;
            $t['step_id'] = $unit_id;
            $t['status'] = 1;
            $t['add_time'] = time();

            foreach ($ids as $key => $value) {
                $t['courseware_id'] = $value;
                if (!Db::name('live_step_resource')->insert($t)) {
                    Db::rollback();
                    return $this->outputAjax('添加失败！');
                }

                if (!Db::name('courseware')->where('id', '=', $value)->inc('num_of_add')->update()) {
                    Db::rollback();
                    return $this->outputAjax('添加失败[1]');
                }
            }
            Db::name('live')->where('id', '=', $live_id)->update(['update_time'=>time()]);

            Db::commit();
            return $this->outputAjax('添加成功！',0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    /**
     * 课件排序
     * @date: 2019年3月27日
     * @author: Administrator
     * @return:
     */
    public function sortCourseware(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $live_id = $request->post('live_id');
        if (!$live_id) {
            return json(['code'=>500,'msg'=>'缺少班级id']);
        }

        $sorts = $request->param('resource/a');

        try {
            if (is_array($sorts)) {
                foreach ($sorts as $key => $value){
                    Db::name('live_step_resource')
                        ->where('id', '=', $value)
                        ->where('live_id', '=', $live_id)
                        ->update(['sort'=>$key]);
                }
                return json(['code'=>200,'msg'=>'排序成功']);
            } else {
                return json(['code'=>500,'msg'=>'缺少排序数据']);
            }
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    // 删除课件
    public function deleteResource(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $live_id = $request->post('live_id');
        if (!$live_id) {
            return json(['code'=>500,'msg'=>'缺少班级id']);
        }

        $id = $request->post('id');

        Db::startTrans();
        try {
            $res = Db::name('live_step_resource')->where('id', '=', $id)->where('live_id', '=', $live_id)->find();

            if (!Db::name('live_step_resource')->where('id', '=', $id)->where('live_id', '=', $live_id)->update(['status' => 3])) {
                Db::rollback();
                return $this->outputAjax('删除失败！');
            }

            if (!Db::name('courseware')->where('id', '=', $res['courseware_id'])->dec('num_of_add')->update()) {
                Db::rollback();
                return $this->outputAjax('删除失败[1]');
            }

            Db::commit();
            return $this->outputAjax('删除成功！', 0);

        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    // 下载记录
    public function download(Request $request)
    {
        $live_id = $request->get('live_id');

        $data = Db::name('live_step_resource')
            ->alias('a')
            ->join('o_courseware b', 'a.courseware_id=b.id','left')
            ->field('a.id, a.live_id, b.title, b.id as courseware_id')
            ->where('a.live_id', '=', $live_id)
            ->where('b.type', '=', 2)
            ->select();

        View::assign('data', $data);
        View::assign('live_id', $live_id);
        return View::fetch();
    }

    // 下载记录加载
    public function getDownloadList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();

        $where = [];

        if (!empty($get['resource_id'])) {
            $where['a.resource_id'] = $get['resource_id'];
        }

        $where['a.class_id'] = $get['live_id'];

        $where['a.type'] = 3;

        $total = Db::table('o_download_log')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->where($where)
            ->count();

        $rows = Db::table('o_download_log')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->where($where)
            ->order('a.add_time', 'desc')
            ->field('a.id, a.name as resource_name, a.class_id, a.resource_id, b.name, b.department_name, b.division, a.userid, a.add_time')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                }
            }
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    // 导出下载记录
    public function exportDownloadList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $get = $request->get();

        $where = [];

        if (!empty($get['resource_id'])) {
            $where[] = ['a.resource_id', '=', $get['resource_id']];
        }

        $where[] = ['a.class_id', '=', $get['live_id']];

        $where[] = ['a.type', '=', 3];

        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '课件下载记录'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['课件名称(CN)', 'Carol ID', '姓名', 'Division', '部门', '下载时间']);

        $total = Db::table('o_download_log')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->where($where)
            ->count();


        $nums = 2000; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;

            $rows = Db::table('o_download_log')
                ->alias('a')
                ->join('o_members b', 'a.userid=b.userid', 'left')
                ->where($where)
                ->order('a.add_time', 'desc')
                ->field('a.id, a.name as resource_name, a.class_id, a.resource_id, b.name, b.department_name, b.division, a.userid, a.add_time')
                ->limit($start, $nums)
                ->select()
                ->toArray();

            foreach ($rows as $v) {
                $count = mb_strlen($v['userid']);
                if ($count == 6) {
                    if (is_numeric($v['userid'])) {
                        $userid = "'00".$v['userid'];
                    }
                }

                $arr = [
                    $v['resource_name'],
                    $userid,
                    $v['name'],
                    $v['division'],
                    $v['department_name'],
                    date('Y-m-d H:i',$v['add_time']),
                ];
                fputcsv($fp, $arr);
            }
            //每1千条数据就刷新缓冲区
            ob_flush();
            flush();
        }

    }


    // 课程评价
    public function evaluateLog(Request $request)
    {
        $live_id = $request->get('live_id');

        View::assign('live_id', $live_id);
        return View::fetch();
    }


    public function getEvaluateLogList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $where = [];

        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['b.name|b.userid', 'like', '%' . $get['key'] . '%'];
            }
        }

        $where[] = ['a.aid', '=', $get['live_id']];
        $where[] = ['a.is_review', '=', 0];
        $where[] = ['a.type', '=', 3];

        $total = Db::table('o_subject_submit')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->where($where)
            ->count();

        $rows = Db::table('o_subject_submit')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->where($where)
            ->order('a.id', 'desc')
            ->field('a.id, a.aid as live_id, a.start_time, a.submit_time, b.department_name, b.division, b.name, a.userid')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            $start_time = $v['start_time'];
            $submit_time = $v['submit_time'];
            $v['start_time'] = date('Y-m-d H:i:s', $v['start_time']);
            $v['submit_time'] = date('Y-m-d H:i:s', $v['submit_time']);
            $v['learning_time'] = $submit_time - $start_time;

            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                }
            }
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    //+ 课程评价导出
    public function exportEvaluateLog(Request $request)
    {

        if (!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        ob_end_clean();
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '课程评价明细' . date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['工号', '姓名', 'Division', '部门', '开始学习时间', '学习时长(s)', '提交时间']);


        $get = $request->get();
        $where = [];

        if (!empty($get['key'])) {
            $where[] = ['b.name|b.userid', 'like', '%' . $get['key'] . '%'];
        }

        $where[] = ['a.aid', '=', $get['live_id']];
        $where[] = ['a.is_review', '=', 0];
        $where[] = ['a.type', '=', 3];

        $total = Db::table('o_subject_submit')
            ->alias('a')
            ->join('o_members b', 'a.userid=b.userid', 'left')
            ->where($where)
            ->count();

        $nums = 10; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;

            $rows = Db::table('o_subject_submit')
                ->alias('a')
                ->join('o_members b', 'a.userid=b.userid', 'left')
                ->where($where)
                ->order('a.id', 'desc')
                ->field('a.id, a.aid as live_id, a.start_time, a.submit_time, b.department_name, b.division, b.name, a.userid')
                ->limit($start, $nums)
                ->select()
                ->toArray();

            foreach ($rows as &$v) {

                $start_time = date('Y-m-d H:i:s', $v['start_time']);
                $submit_time = date('Y-m-d H:i:s', $v['submit_time']);
                $learning_time = $v['submit_time'] - $v['start_time'];

                $count = mb_strlen($v['userid']);
                if ($count == 6) {
                    if (is_numeric($v['userid'])) {
                        $userid = "'00".$v['userid'];
                    } else {
                        $userid = $v['userid'];
                    }
                } else {
                    $userid = $v['userid'];
                }

                $arr = [
                    $userid,
                    $v['name'],
                    $v['division'],
                    $v['department_name'],
                    $start_time,
                    $learning_time,
                    $submit_time
                ];

                fputcsv($fp, $arr);
            }
            flush();
        }
    }


    //+ 删除课程评价
    public function deleteEvaluateLog(Request $request)
    {
        $id = $request->post('id');
        $live_id = $request->post('live_id');

        if (!$id) {
            return $this->outputAjax('参数不足！');
        }

        Db::startTrans();
        try {

            $inf = Db::name('subject_submit')
                ->where('id', '=', $id)
                ->find();


            $answer = Db::name('subject_answer')
                ->where('aid', '=', $live_id)
                ->where('userid', '=', $inf['userid'])
                ->where('test_type', '=', 3)
                ->where('is_review', '=', 0)
                ->delete();
            if (!$answer) {
                Db::rollback();
                return $this->outputAjax('删除失败[2]！');
            }

            $submit = Db::name('subject_submit')
                ->where('id', '=', $id)
                ->delete();
            if (!$submit) {
                Db::rollback();
                return $this->outputAjax('删除失败[3]！');
            }

            Db::commit();
            return $this->outputAjax('删除成功！', 0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    //课程评价数据分析
    public function evaluateAnalyze(Request $request)
    {
        $get = $request->get();

        $subject = Db::name('subject')
            ->where('id', 'in', '1,2')
            ->field('id, subject, subject_type')
            ->select()
            ->toArray();

        // 做题人数或计分人数
        $members_total = 0;
        // 总分
        $total_points = 0;

        foreach ($subject as &$v) {
            $v['subject_type_name'] = '打分项';

            $v['subject_id'] = $v['id'];
            $option = Db::name('subject_option')
                ->where('subject_id', '=', $v['id'])
                ->field('id as option_id, subject_id, title, letter')
                ->select()
                ->toArray();

            $v['options_count'] = count($option);


            if ($v['subject_type'] == 4) {

                foreach ($option as &$val) {

                    if ($v['id'] == 2) {
                        if ($val['letter'] != 'A') {
                            $members_count = Db::name('subject_answer')
                                ->where('aid', '=', $get['live_id'])
                                ->where('subject_id', '=', $val['subject_id'])
                                ->where('answer', '=', $val['option_id'])
                                ->where('type', '=', 4)
                                ->where('test_type', '=', 3)
                                ->where('is_review', '=', 0)
                                ->count();
                            $members_total += $members_count;
                            $fraction = $this->fraction($val['letter']);
                            $total_points += $members_count*$fraction;
                        }
                    }


                    //+选择人数
                    $count = Db::name('subject_answer')
                        ->where('aid', '=', $get['live_id'])
                        ->where('subject_id', '=', $val['subject_id'])
                        ->where('answer', '=', $val['option_id'])
                        ->where('type', '=', 4)
                        ->where('test_type', '=', 3)
                        ->where('is_review', '=', 0)
                        ->count();
                    $val['selected_count'] = $count;

                    //+占比
                    $count1 = Db::name('subject_answer')
                        ->where('aid', '=', $get['live_id'])
                        ->where('subject_id', '=', $val['subject_id'])
                        ->where('test_type', '=', 3)
                        ->where('is_review', '=', 0)
                        ->group('userid')
                        ->count();

                    if ($count1 == 0) {
                        $val['percentage'] = '0%';
                    } else {
                        $val['percentage'] = number_format(($count/$count1)*100, 1).'%';
                    }
                }
            }


            $v['options'] = $option;
        }
        // 平均分
        $average = empty($total_points) ? 0 : number_format(($total_points/$members_total), 2);

        $total = Db::name('subject_answer')
            ->where('aid', '=', $get['live_id'])
            ->where('is_review', '=', 0)
            ->group('userid')
            ->count();
        View::assign('total', $total);
        View::assign('subject', $subject);
        View::assign('average', $average);

        View::assign('live_id', $get['live_id']);
        return View::fetch();
    }


    //导出课程评价数据分析
    public function exportEvaluateAnalysis(Request $request)
    {

        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $get = $request->get();


        ob_end_clean ();
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '课程评价数据分析'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['题目', '选项', '选择率', '人数', '平均值', '前端备注']);


        $subject = Db::name('subject')
            ->where('id', 'in', '1,2')
            ->field('id, subject, subject_type')
            ->select()
            ->toArray();

        $data = [];
        $members_total = 0;
        $total_points = 0;

        foreach ($subject as &$v) {
            $subject_type_name = '打分项';


            $option = Db::name('subject_option')
                ->where('subject_id', '=', $v['id'])
                ->field('id as option_id, subject_id, title, letter')
                ->select()
                ->toArray();

            if ($v['subject_type'] == 4) {
                $data1 = [];
                foreach ($option as &$val) {

                    if ($v['id'] == 2) {
                        if ($val['letter'] != 'A') {
                            $members_count = Db::name('subject_answer')
                                ->where('aid', '=', $get['live_id'])
                                ->where('subject_id', '=', $val['subject_id'])
                                ->where('answer', '=', $val['option_id'])
                                ->where('type', '=', 4)
                                ->where('test_type', '=', 3)
                                ->where('is_review', '=', 0)
                                ->count();
                            $members_total += $members_count;
                            $fraction = $this->fraction($val['letter']);
                            $total_points += $members_count*$fraction;
                        }
                    }


                    //+选择人数
                    $count = Db::name('subject_answer')
                        ->where('subject_id', '=', $val['subject_id'])
                        ->where('aid', '=', $get['live_id'])
                        ->where('answer', '=', $val['option_id'])
                        ->where('type', '=', 4)
                        ->where('test_type', '=', 3)
                        ->where('is_review', '=', 0)
                        ->count();

                    //+占比
                    $count1 = Db::name('subject_answer')
                        ->where('subject_id', '=', $val['subject_id'])
                        ->where('aid', '=', $get['live_id'])
                        ->where('test_type', '=', 3)
                        ->where('is_review', '=', 0)
                        ->group('userid')
                        ->count();

                    $arr = [
                        'subject' => $v['subject'].'('.$subject_type_name.')',
                        'title' => $val['title'],
                        'percentage' => $count1 == 0 ? '0%' : number_format(($count/$count1)*100, 1).'%',
                        'selected_count' => $count,
                    ];
                    array_push($data1, $arr);
                }

                $remarks = Db::name('subject_answer')
                    ->where('aid', '=', $get['live_id'])
                    ->where('subject_id', '=', $v['id'])
                    ->where('type', '=', 4)
                    ->where('test_type', '=', 3)
                    ->where('is_review', '=', 0)
                    ->column('remarks');

                foreach ($data1 as &$d) {
                    $arr = [
                        'subject' => $d['subject'],
                        'title' => $d['title'],
                        'percentage' => $d['percentage'],
                        'selected_count' => $d['selected_count'],
                    ];
                    $arr['remarks'] = implode('|', $remarks);
                    array_push($data, $arr);
                }
            }

        }
        $average = empty($total_points) ? 0 : number_format(($total_points/$members_total), 2);
        foreach ($data as &$v) {
            $arr = [
                $v['subject'],
                $v['title'],
                $v['percentage'],
                $v['selected_count'],
                $average,
                $v['remarks']
            ];

            fputcsv($fp, $arr);
        }
        flush();
    }

    protected function fraction($key)
    {
        $data = ['B' => 1, 'C' => 2, 'D' => 3, 'E' => 4, 'F' => 5, 'G' => 6, 'H' => 7, 'I' => 8, 'J' => 9, 'K' => 10];
        return $data[$key];
    }
}